<template>
  <div class="query-sql">
    <!-- 数据库选择和连接状态 -->
    <el-card class="database-selector">
      <div class="database-header">
        <div class="database-select">
          <el-select
            v-model="selectedDatabase"
            placeholder="请选择数据库实例"
            style="width: 350px"
            @change="handleDatabaseChange"
          >
            <el-option
              v-for="db in databases"
              :key="db.id"
              :label="`${db.name} (${db.database_type})`"
              :value="db.id"
            >
              <div class="database-option">
                <div class="db-info">
                  <span class="db-name">{{ db.name }}</span>
                  <span class="db-detail">{{ db.host }}:{{ db.port }}/{{ db.database_name }}</span>
                </div>
                <el-tag :type="getDbTypeTag(db.database_type)" size="small">
                  {{ db.database_type.toUpperCase() }}
                </el-tag>
              </div>
            </el-option>
          </el-select>

          <el-button
            type="success"
            size="small"
            @click="showAddConnectionDialog"
          >
            <el-icon><Plus /></el-icon>
            新建连接
          </el-button>

          <el-button
            v-if="selectedDatabase"
            type="primary"
            size="small"
            @click="testConnection"
            :loading="testingConnection"
          >
            <el-icon><Link /></el-icon>
            测试连接
          </el-button>

          <el-button
            v-if="selectedDatabase"
            size="small"
            @click="loadDatabaseSchema"
            :loading="loadingSchema"
          >
            <el-icon><FolderOpened /></el-icon>
            查看结构
          </el-button>
        </div>

        <div class="connection-status">
          <el-tag
            v-if="connectionStatus"
            :type="connectionStatus.success ? 'success' : 'danger'"
            size="small"
          >
            <el-icon>
              <CircleCheck v-if="connectionStatus.success" />
              <CircleClose v-else />
            </el-icon>
            {{ connectionStatus.message }}
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- SQL编辑器和侧边栏 -->
    <div class="editor-layout">
      <!-- 左侧：SQL编辑器 -->
      <div class="editor-main">
        <el-card>
          <template #header>
            <div class="editor-header">
              <span>SQL编辑器</span>
              <div class="editor-actions">
                <el-button @click="reinitializeEditor" type="warning" size="small">
                  <el-icon><Refresh /></el-icon>
                  重置编辑器
                </el-button>
              </div>
            </div>
          </template>

          <!-- 使用简化的纯文本编辑器 -->
          <div class="simple-editor-container">
            <div class="editor-toolbar">
              <div class="toolbar-left">
                <el-button-group>
                  <el-button @click="newQuery" size="small">
                    <el-icon><Plus /></el-icon>
                    新建
                  </el-button>
                  <el-button @click="saveQuery" :disabled="!queryForm.sql_content" size="small">
                    <el-icon><Document /></el-icon>
                    保存
                  </el-button>
                  <el-button @click="showHistory" size="small">
                    <el-icon><Clock /></el-icon>
                    历史
                  </el-button>
                </el-button-group>
              </div>
              <div class="toolbar-right">
                <el-tag type="success" size="small">稳定版编辑器</el-tag>
              </div>
            </div>

            <!-- 只使用纯文本编辑器，避免所有复杂性 -->
            <PlainTextEditor
              ref="sqlEditorRef"
              v-model="queryForm.sql_content"
              :selected-database="selectedDatabase"
              :executing="executing"
              :rows="20"
              placeholder="请输入SQL查询语句..."
              @execute="executeQuery"
            />
          </div>
        </el-card>
      </div>

      <!-- 右侧：数据库结构 -->
      <div class="sidebar" v-if="showSidebar">
        <el-card>
          <template #header>
            <div class="sidebar-header">
              <span>数据库结构</span>
              <el-button size="small" text @click="showSidebar = false">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </template>

          <div v-if="databaseSchema" class="schema-tree">
            <el-tree
              :data="schemaTreeData"
              :props="{ children: 'children', label: 'label' }"
              node-key="id"
              :expand-on-click-node="false"
              @node-click="handleSchemaNodeClick"
            >
              <template #default="{ node, data }">
                <div class="schema-node">
                  <el-icon>
                    <Folder v-if="data.type === 'table'" />
                    <Document v-else />
                  </el-icon>
                  <span>{{ data.label }}</span>
                  <span v-if="data.dataType" class="data-type">{{ data.dataType }}</span>
                </div>
              </template>
            </el-tree>
          </div>

          <div v-else class="schema-empty">
            <el-empty description="请先选择数据库并加载结构" />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 查询结果 -->
    <el-card v-if="queryResult" class="result-card">
      <template #header>
        <div class="result-header">
          <div class="result-title">
            <span>查询结果</span>
            <el-tag v-if="queryResult.sql_type" :type="getSqlTypeTag(queryResult)" size="small">
              {{ queryResult.sql_type }}
            </el-tag>
          </div>
          <div class="result-stats">
            <el-tag type="success" size="small">
              <el-icon><Timer /></el-icon>
              {{ queryResult.execution_time }}s
            </el-tag>
            <el-tag type="info" size="small">
              <el-icon><DataLine /></el-icon>
              {{ queryResult.row_count || queryResult.affected_rows || 0 }} 行
            </el-tag>
            <el-button
              v-if="queryResult.rows && queryResult.rows.length > 0"
              size="small"
              @click="exportResult"
            >
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 成功消息 -->
      <div v-if="queryResult.message && !queryResult.rows?.length" class="result-message">
        <el-alert :title="queryResult.message" type="success" :closable="false" />
      </div>

      <!-- 数据表格 -->
      <div v-if="queryResult.rows && queryResult.rows.length > 0" class="result-table">
        <el-table
          :data="paginatedRows"
          border
          stripe
          style="width: 100%"
          max-height="500"
          :default-sort="{ prop: '0', order: 'ascending' }"
        >
          <el-table-column
            v-for="(column, index) in queryResult.columns"
            :key="index"
            :prop="index.toString()"
            :label="column"
            :sortable="true"
            show-overflow-tooltip
            min-width="120"
          />
        </el-table>

        <!-- 分页 -->
        <div class="result-pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 200, 500]"
            :total="queryResult.rows.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新建数据库连接对话框 -->
    <el-dialog
      v-model="addConnectionDialogVisible"
      title="新建数据库连接"
      width="600px"
      :close-on-click-modal="false"
      @opened="onDialogOpened"
    >
      <el-form
        ref="connectionFormRef"
        :model="connectionForm"
        :rules="connectionRules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="连接名称" prop="name">
          <el-input
            v-model="connectionForm.name"
            placeholder="请输入连接名称，如：生产环境MySQL"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="数据库类型" prop="database_type">
          <el-select
            v-model="connectionForm.database_type"
            placeholder="请选择数据库类型"
            style="width: 100%"
            @change="handleDatabaseTypeChange"
          >
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="SQLite" value="sqlite" />
            <el-option label="Oracle" value="oracle" />
            <el-option label="SQL Server" value="sqlserver" />
            <el-option label="MongoDB" value="mongodb" />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="服务器地址" prop="host">
              <el-input
                v-model="connectionForm.host"
                placeholder="如：192.168.1.100 或 db.example.com"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="端口" prop="port">
              <el-input-number
                v-model="connectionForm.port"
                :key="`port-${connectionForm.database_type}`"
                :min="0"
                :max="65535"
                style="width: 100%"
                placeholder="端口号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="数据库名称" prop="database_name">
          <el-input
            v-model="connectionForm.database_name"
            placeholder="请输入数据库名称"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="connectionForm.username"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="connectionForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述">
          <el-input
            v-model="connectionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入连接描述（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 连接测试结果 -->
        <el-form-item v-if="connectionTestResult" label="连接状态">
          <el-alert
            :title="connectionTestResult.message"
            :type="connectionTestResult.success ? 'success' : 'error'"
            :closable="false"
            show-icon
          >
            <template v-if="connectionTestResult.success && connectionTestResult.details">
              <div style="margin-top: 8px; font-size: 12px;">
                <div>连接时间: {{ connectionTestResult.details.connection_time }}s</div>
                <div v-if="connectionTestResult.details.version">
                  数据库版本: {{ connectionTestResult.details.version }}
                </div>
              </div>
            </template>
          </el-alert>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addConnectionDialogVisible = false">取消</el-button>
          <el-button
            type="info"
            @click="testNewConnection"
            :loading="testingNewConnection"
          >
            <el-icon><Link /></el-icon>
            测试连接
          </el-button>
          <el-button
            type="primary"
            @click="saveConnection"
            :loading="savingConnection"
            :disabled="!connectionTestResult?.success"
          >
            <el-icon><Check /></el-icon>
            保存连接
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Link, FolderOpened, CircleCheck, CircleClose, Close, Folder, Timer, DataLine, Download, Refresh,
  Plus, Document, Clock, Check
} from '@element-plus/icons-vue'
import { sqlAPI } from '@/api/sql'
import PlainTextEditor from '@/components/PlainTextEditor.vue'

// 响应式数据
const queryForm = ref({
  sql_content: ''
})

const databases = ref([])
const selectedDatabase = ref(null)
const executing = ref(false)
const queryResult = ref(null)
const connectionStatus = ref(null)
const testingConnection = ref(false)
const databaseSchema = ref(null)
const loadingSchema = ref(false)
const showSidebar = ref(false)
const sqlAnalysis = ref(null)

// 编辑器引用
const sqlEditorRef = ref(null)

// 新建连接相关
const addConnectionDialogVisible = ref(false)
const connectionFormRef = ref(null)
const connectionForm = ref({
  name: '',
  database_type: 'mysql',
  host: 'localhost',
  port: 3306,
  database_name: '',
  username: '',
  password: '',
  description: ''
})
const connectionTestResult = ref(null)
const testingNewConnection = ref(false)
const savingConnection = ref(false)

// 表单验证规则
const connectionRules = {
  name: [
    { required: true, message: '请输入连接名称', trigger: 'blur' },
    { min: 2, max: 100, message: '连接名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  database_type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入服务器地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 0, max: 65535, message: '端口号必须在 0-65535 之间', trigger: 'blur' }
  ],
  database_name: [
    { required: true, message: '请输入数据库名称', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(100)

// 计算属性
const paginatedRows = computed(() => {
  if (!queryResult.value?.rows) return []
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return queryResult.value.rows.slice(start, end)
})

const schemaTreeData = computed(() => {
  if (!databaseSchema.value?.tables) return []

  return databaseSchema.value.tables.map(table => ({
    id: `table_${table.name}`,
    label: table.name,
    type: 'table',
    children: table.columns.map(column => ({
      id: `column_${table.name}_${column.name}`,
      label: column.name,
      type: 'column',
      dataType: column.type,
      nullable: column.nullable,
      primaryKey: column.primary_key
    }))
  }))
})

// 加载数据库实例
const loadDatabases = async () => {
  try {
    const response = await sqlAPI.getDatabaseInstances()
    databases.value = response.data?.results || response.data || []
  } catch (error) {
    console.error('加载数据库实例失败:', error)
    ElMessage.error('加载数据库实例失败')
  }
}

// 数据库选择变化
const handleDatabaseChange = (databaseId) => {
  connectionStatus.value = null
  databaseSchema.value = null
  showSidebar.value = false

  if (databaseId) {
    // 自动测试连接
    testConnection()
  }
}

// 测试数据库连接
const testConnection = async () => {
  if (!selectedDatabase.value) return

  testingConnection.value = true
  try {
    const response = await sqlAPI.testDatabaseConnection(selectedDatabase.value)
    connectionStatus.value = response.data

    if (response.data.success) {
      ElMessage.success('数据库连接成功')
    } else {
      ElMessage.error(`连接失败: ${response.data.message}`)
    }
  } catch (error) {
    console.error('测试连接失败:', error)
    connectionStatus.value = {
      success: false,
      message: '连接测试失败'
    }
    ElMessage.error('连接测试失败')
  } finally {
    testingConnection.value = false
  }
}

// 加载数据库结构
const loadDatabaseSchema = async () => {
  if (!selectedDatabase.value) return

  loadingSchema.value = true
  try {
    const response = await sqlAPI.getDatabaseSchema(selectedDatabase.value)
    databaseSchema.value = response.data
    showSidebar.value = true
    ElMessage.success(`加载完成，共 ${response.data.total_tables} 个表`)
  } catch (error) {
    console.error('加载数据库结构失败:', error)
    ElMessage.error('加载数据库结构失败')
  } finally {
    loadingSchema.value = false
  }
}

// 执行SQL查询
const executeQuery = async (sqlContent) => {
  if (!selectedDatabase.value || !sqlContent) {
    ElMessage.warning('请选择数据库实例并输入SQL语句')
    return
  }

  // 检查危险操作
  if (sqlAnalysis.value?.requires_confirmation) {
    try {
      await ElMessageBox.confirm(
        `您即将执行 ${sqlAnalysis.value.sql_type} 操作，这可能会对数据造成不可逆的影响。确定要继续吗？`,
        '危险操作确认',
        {
          confirmButtonText: '确定执行',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
      )
    } catch {
      return
    }
  }

  executing.value = true
  try {
    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: sqlContent,
      limit: 1000
    })

    queryResult.value = response.data.result
    currentPage.value = 1

    ElMessage.success(response.data.message || '查询执行成功')
  } catch (error) {
    console.error('查询执行失败:', error)
    ElMessage.error(error.response?.data?.error || '查询执行失败')
    queryResult.value = null
  } finally {
    executing.value = false
  }
}

// SQL分析处理（简化版本暂时不需要）
// const handleSQLAnalyze = (analysis) => {
//   sqlAnalysis.value = analysis
// }

// 新建查询
const newQuery = () => {
  console.log('新建查询被点击')
  try {
    // 清空表单数据
    queryForm.value.sql_content = ''
    queryResult.value = null
    sqlAnalysis.value = null

    ElMessage.success('已清空编辑器，可以开始新的查询')
  } catch (error) {
    console.error('新建查询失败:', error)
    ElMessage.error('新建查询失败')
  }
}

// 保存查询
const saveQuery = (content) => {
  console.log('保存查询:', content)
  // TODO: 实现查询保存功能
  ElMessage.info('保存功能开发中...')
}

// 显示历史
const showHistory = () => {
  // TODO: 实现历史查询功能
  ElMessage.info('历史功能开发中...')
}

// 编辑器切换功能已移除，使用稳定的纯文本编辑器

// 重新初始化编辑器
const reinitializeEditor = async () => {
  try {
    ElMessage.info('正在重新初始化编辑器...')

    // 清空当前内容
    queryForm.value.sql_content = ''

    // 重置纯文本编辑器
    if (sqlEditorRef.value && sqlEditorRef.value.isReady()) {
      sqlEditorRef.value.clearEditor()
    }

    ElMessage.success('编辑器重新初始化完成')
  } catch (error) {
    console.error('重新初始化编辑器失败:', error)
    ElMessage.error('重新初始化编辑器失败')
  }
}

// 处理结构树节点点击
const handleSchemaNodeClick = (data) => {
  if (data.type === 'table') {
    // 插入表名
    const tableName = data.label
    queryForm.value.sql_content += `SELECT * FROM ${tableName} LIMIT 10;\n`
  } else if (data.type === 'column') {
    // 插入列名
    const columnName = data.label
    queryForm.value.sql_content += columnName
  }
}

// 导出结果
const exportResult = () => {
  if (!queryResult.value?.rows?.length) return

  try {
    // 构建CSV内容
    const headers = queryResult.value.columns.join(',')
    const rows = queryResult.value.rows.map(row =>
      row.map(cell => `"${cell}"`).join(',')
    ).join('\n')

    const csvContent = `${headers}\n${rows}`

    // 创建下载链接
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)

    link.setAttribute('href', url)
    link.setAttribute('download', `query_result_${new Date().getTime()}.csv`)
    link.style.visibility = 'hidden'

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 获取数据库类型标签
const getDbTypeTag = (type) => {
  const typeMap = {
    mysql: 'success',
    postgresql: 'primary',
    sqlite: 'info',
    oracle: 'warning'
  }
  return typeMap[type.toLowerCase()] || 'info'
}

// 获取SQL类型标签
const getSqlTypeTag = (result) => {
  if (result.is_dangerous) return 'danger'
  if (result.is_readonly) return 'success'
  if (result.is_dml) return 'warning'
  return 'info'
}

// 显示新建连接对话框
const showAddConnectionDialog = () => {
  // 重置表单并设置默认值
  connectionForm.value = {
    name: '',
    database_type: 'mysql',
    host: 'localhost',
    port: 3306,
    database_name: '',
    username: '',
    password: '',
    description: ''
  }
  connectionTestResult.value = null
  addConnectionDialogVisible.value = true
}

// 对话框打开后的回调
const onDialogOpened = () => {
  // 清除表单验证状态
  nextTick(() => {
    if (connectionFormRef.value) {
      connectionFormRef.value.clearValidate()
    }
  })
}

// 端口映射配置
const defaultPorts = {
  mysql: 3306,
  postgresql: 5432,
  sqlite: 0,
  oracle: 1521,
  sqlserver: 1433,
  mongodb: 27017
}

// 数据库类型变化时更新默认端口
const handleDatabaseTypeChange = (type) => {
  const newPort = defaultPorts[type] || 3306
  connectionForm.value.port = newPort
}

// 监听数据库类型变化
watch(
  () => connectionForm.value.database_type,
  (newType) => {
    if (newType) {
      handleDatabaseTypeChange(newType)
    }
  },
  { immediate: true }
)

// 测试新连接
const testNewConnection = async () => {
  // 先验证表单
  try {
    await connectionFormRef.value.validate()
  } catch (error) {
    ElMessage.warning('请填写完整的连接信息')
    return
  }

  testingNewConnection.value = true
  connectionTestResult.value = null

  try {
    // 创建临时连接进行测试
    const testData = {
      name: connectionForm.value.name + '_test',
      host: connectionForm.value.host,
      port: connectionForm.value.port,
      database_type: connectionForm.value.database_type,
      username: connectionForm.value.username,
      password: connectionForm.value.password,
      database_name: connectionForm.value.database_name,
      description: 'Test connection'
    }

    // 先创建临时实例
    const createResponse = await sqlAPI.createDatabaseInstance(testData)
    const tempInstanceId = createResponse.data.id

    try {
      // 测试连接
      const testResponse = await sqlAPI.testDatabaseConnection(tempInstanceId)

      if (testResponse.data.success) {
        connectionTestResult.value = {
          success: true,
          message: '连接测试成功！',
          details: {
            connection_time: testResponse.data.connection_time,
            version: testResponse.data.version
          }
        }
        ElMessage.success('数据库连接测试成功')
      } else {
        connectionTestResult.value = {
          success: false,
          message: `连接失败: ${testResponse.data.message}`
        }
        ElMessage.error(`连接测试失败: ${testResponse.data.message}`)
      }
    } finally {
      // 删除临时实例
      try {
        await sqlAPI.deleteDatabaseInstance(tempInstanceId)
      } catch (deleteError) {
        console.warn('删除临时实例失败:', deleteError)
      }
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    connectionTestResult.value = {
      success: false,
      message: `连接测试失败: ${error.response?.data?.error || error.message}`
    }
    ElMessage.error('连接测试失败')
  } finally {
    testingNewConnection.value = false
  }
}

// 保存连接
const saveConnection = async () => {
  if (!connectionTestResult.value?.success) {
    ElMessage.warning('请先测试连接成功后再保存')
    return
  }

  savingConnection.value = true

  try {
    const response = await sqlAPI.createDatabaseInstance(connectionForm.value)

    ElMessage.success('数据库连接保存成功')
    addConnectionDialogVisible.value = false

    // 重新加载数据库列表
    await loadDatabases()

    // 自动选择新创建的数据库
    selectedDatabase.value = response.data.id
    handleDatabaseChange(response.data.id)

  } catch (error) {
    console.error('保存连接失败:', error)
    ElMessage.error(`保存连接失败: ${error.response?.data?.error || error.message}`)
  } finally {
    savingConnection.value = false
  }
}

onMounted(() => {
  loadDatabases()
})
</script>

<style scoped>
.query-sql {
  padding: 20px;
  height: calc(100vh - 120px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 数据库选择器 */
.database-selector {
  flex-shrink: 0;
}

.database-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.database-select {
  display: flex;
  align-items: center;
  gap: 10px;
}

.database-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.db-info {
  display: flex;
  flex-direction: column;
}

.db-name {
  font-weight: 500;
  color: #303133;
}

.db-detail {
  font-size: 12px;
  color: #909399;
}

.connection-status {
  display: flex;
  align-items: center;
}

/* 编辑器布局 */
.editor-layout {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0;
}

.editor-main {
  flex: 1;
  min-width: 0;
}

.sidebar {
  width: 300px;
  flex-shrink: 0;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 数据库结构树 */
.schema-tree {
  max-height: 400px;
  overflow-y: auto;
}

.schema-node {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
}

.data-type {
  color: #909399;
  font-size: 11px;
  margin-left: auto;
}

.schema-empty {
  text-align: center;
  padding: 40px 20px;
}

/* 查询结果 */
.result-card {
  flex-shrink: 0;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.result-stats {
  display: flex;
  align-items: center;
  gap: 10px;
}

.result-message {
  margin-bottom: 20px;
}

.result-table {
  max-height: 500px;
  overflow: auto;
}

.result-pagination {
  margin-top: 20px;
  text-align: right;
}

.simple-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 新建连接对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .editor-layout {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .query-sql {
    padding: 10px;
  }

  .database-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .database-select {
    flex-direction: column;
    align-items: stretch;
  }

  .result-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .result-stats {
    justify-content: center;
  }
}
</style>
